package com.thread.sync.sync11;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

//使用信号量来限流
public class UseSemaphore {

    public static void main(String[] args) {
        ExecutorService pool = Executors.newCachedThreadPool();
        //声明5个线程的信号量,即只能5个线程同时访问
        final Semaphore semp = new Semaphore(5);
        //模拟20个客户端访问
        for (int i = 0; i < 20; i++) {
            final int num = i;
            pool.execute(new Thread(() -> {
                //获取信号量许可
                try {
                    semp.acquire();
                    System.out.println(num + "号客户端允许访问.....");
                    //模拟实际业务逻辑
                    Thread.sleep(2000);
                    //访问完成,释放,下一个线程才能开始执行
                    semp.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }));
        }
    }
}
